﻿using BusinessManage.Common;
using CPFrameWork.Global;
using CPFrameWork.UIInterface.Form;
using CPFrameWork.Utility.DbOper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using BusinessManage.ConfirmSign;

namespace BusinessManage.UpdateForm
{
    public class OrderOperateLog : CPFrameWork.UIInterface.Form.ICPFormAfterSave
    {
        public void AfterSave(ICPFormAfterSaveEventArgs e)
        {

        }
    }


    /// <summary>
    /// 订单拆户
    /// 1、将为未进行拆户的剩余部分进行存储，此车此订单下剩余的商品、数量
    /// 2、更新任务与车辆关系表 车辆运输状态
    /// 3、插入日志，记录拆户操作
    /// </summary>
    public class OrderChaiLog : CPFrameWork.UIInterface.Form.ICPFormAfterSave
    {
        public void AfterSave(ICPFormAfterSaveEventArgs e)
        {
            StringBuilder stringb_order = new StringBuilder();
            DbHelper dbHelper = new DbHelper(e.Form.DbIns, CPAppContext.CurDbType());
            string TaskId = e.GetFieldValue(e.Form.MainTableName, "TaskId", 0);
            string OrderId = e.GetFieldValue(e.Form.MainTableName, "OrderId", 0);
            string UserId = e.GetFieldValue(e.Form.MainTableName, "CreateUserId", 0);
            string UserName = e.GetFieldValue(e.Form.MainTableName, "CreateUserName", 0);
            string CarNumber = e.GetFieldValue(e.Form.MainTableName, "CarNumber", 0);
            string timenow = DateTime.Now.ToString();
            string OperateDescribe = UserName + "在" + timenow + "对任务" + TaskId + "、订单" + OrderId + "进行了拆户操作";


            //获取订单中的客户信息---------------------------------
            string strSql_order = "SELECT CustomerName,CustomerState,CustomerCity,CustomerDistrict,CustomerAddress,CustomerZip,CustomerMobile,CustomerPhone from YW_OrderInfo ";
            strSql_order += " where OrderCode = '" + OrderId + "';";
            stringb_order.Append(strSql_order);
            DataTable dtOrderInfo = dbHelper.ExecuteDataSet(stringb_order.ToString()).Tables[0];
            string CustomerName = dtOrderInfo.Rows[0][0].ToString();
            string CustomerState = dtOrderInfo.Rows[0][1].ToString();
            string CustomerCity = dtOrderInfo.Rows[0][2].ToString();
            string CustomerDistrict = dtOrderInfo.Rows[0][3].ToString();
            string CustomerAddress = dtOrderInfo.Rows[0][4].ToString();
            string CustomerZip = dtOrderInfo.Rows[0][5].ToString();
            string CustomerMobile = dtOrderInfo.Rows[0][6].ToString();
            string CustomerPhone = dtOrderInfo.Rows[0][7].ToString();

            //1、将剩余进行存储：因为每拆一户进行一次提交，故拆户后 剩余部分的，判断下没有记录则进行插入
            //(1)新增拆户信息
            string chaiSql = "if not exists(select * from YW_CustomerSign where TaskId = '" + TaskId + "' and OrderId = '" + OrderId + "' and CarNumber = '"+ CarNumber + "' and SignType = '6') insert into YW_CustomerSign(TaskId, OrderId, CarNumber,CustomerName,CustomerState,CustomerCity,CustomerDistrict,CustomerAddress,CustomerZip,CustomerMobile,CustomerPhone,SignType, IsSign, CreateUserId, CreateUserName, CreateTime) values('" + TaskId + "', '" + OrderId + "', '" + CarNumber + "','" + CustomerName + "','" + CustomerState + "','" + CustomerCity + "','" + CustomerDistrict + "','" + CustomerAddress + "','" + CustomerZip + "','" + CustomerMobile + "','" + CustomerPhone + "', '6', '0', '" + UserId + "', '" + UserName + "', '" + timenow + "')";            
            StringBuilder stirgb_chai = new StringBuilder();
            stirgb_chai.Append(chaiSql);            
            if (stirgb_chai.Length > 0)
            {
                dbHelper.ExecuteNonQuery(stirgb_chai.ToString());
            }
            //(2)得到这条记录的Id,再删除拆户详情表中与此Id关联的数据       
            string strSql_check = "SELECT Id FROM YW_CustomerSign where TaskId  = '" + TaskId + "' and OrderId  = '" + OrderId + "' and CarNumber= '" + CarNumber + "' and SignType = '6';";
            StringBuilder stringb_check = new StringBuilder();
            stringb_check.Append(strSql_check);
            DataTable dtChai = dbHelper.ExecuteDataSet(stringb_check.ToString()).Tables[0];
            string ChaiBaseId = dtChai.Rows[0][0].ToString();
            string deleteSql = "delete from YW_ChaiDetail where SignId='"+ ChaiBaseId + "';";
            StringBuilder stirgb_chaiDelete = new StringBuilder();
            stirgb_chaiDelete.Append(deleteSql);
            if (stirgb_chaiDelete.Length > 0)
            {
                dbHelper.ExecuteNonQuery(stirgb_chaiDelete.ToString());
            }
            //(3)重新计算并存储至拆户详情表 剩余数量=原来的数量+倒入的数量-已经拆户的数量
            string chaiDetailSql = " insert into YW_ChaiDetail ";
            chaiDetailSql += "select distinct'" + ChaiBaseId + "','" + TaskId + "','" + OrderId + "','" + CarNumber + "','','','','',o.GoodsId,o.GoodsName,";
            chaiDetailSql += "ISNULL((select SUM(ISNULL(OrderChickCountInCar,0)) from YW_TaskCarRelation where TaskId='" + TaskId + "' and OrderId='" + OrderId + "' and CarNumber='" + CarNumber + "' and d.GoodsId = o.GoodsId),0)+ISNULL((select SUM(ISNULL(OrderChickCountInCar, 0)) from YW_BringOutIn where TargetTaskId = '" + TaskId + "' and(c.MainDriverId = b.TargetDriverId or c.AssistantDriverId = b.TargetDriverId) and d.GoodsId = o.GoodsId),0)-ISNULL((select SUM(ISNULL(ChickCount,0)) from YW_ChaiDetail where TaskId='" + TaskId + "' and OrderId='" + OrderId + "' and CarNumber='" + CarNumber + "' and d.GoodsId = o.GoodsId),0)  as ChickenCount,";
            chaiDetailSql += "ISNULL((select SUM(ISNULL(HallLossCount,0)) from YW_TaskCarRelation where TaskId='" + TaskId + "' and OrderId='" + OrderId + "' and CarNumber='" + CarNumber + "' and d.GoodsId = o.GoodsId),0)+ISNULL((select SUM(ISNULL(HallLossCount, 0)) from YW_BringOutIn where TargetTaskId = '" + TaskId + "' and(c.MainDriverId = b.TargetDriverId or c.AssistantDriverId = b.TargetDriverId) and d.GoodsId = o.GoodsId),0)- ISNULL((select SUM(ISNULL(LossCount,0)) from YW_ChaiDetail where TaskId='" + TaskId + "' and OrderId='" + OrderId + "' and CarNumber='" + CarNumber + "' and d.GoodsId = o.GoodsId),0)  as CarLossCount ";
            chaiDetailSql += " from YW_TaskCarRelation as c ";
            chaiDetailSql += " left join YW_TaskOrderRelation as o on c.TaskOrderId = o.Id ";           
            chaiDetailSql += " left join YW_ChaiDetail as d on d.TaskId = c.TaskId and d.OrderId = c.OrderId and d.CarNumber = c.CarNumber and d.GoodsId = o.GoodsId ";
            chaiDetailSql += "  left join YW_BringOutIn as b on c.TaskId=b.TargetTaskId and (c.MainDriverId=b.TargetDriverId or c.AssistantDriverId=b.TargetDriverId) ";
            chaiDetailSql += " where c.TaskId='" + TaskId + "' and c.OrderId='" + OrderId + "' and c.CarNumber='" + CarNumber + "'";
            StringBuilder stirgb_chaiDetail = new StringBuilder();
            stirgb_chaiDetail.Append(chaiDetailSql);
            if (stirgb_chaiDetail.Length > 0)
            {
                dbHelper.ExecuteNonQuery(stirgb_chaiDetail.ToString());
            }

            //2、更新任务与车辆关系表 车辆运输状态为“已拆户”
            string strSql = " Update YW_TaskCarRelation ";
            strSql += " set CarDeliveryStatus = '4' ";
            strSql += " where TaskId  = '" + TaskId + "' and OrderId  = '" + OrderId + "' and (MainDriverId= '" + UserId + "' or AssistantDriverId= '" + UserId + "');";

            //3、插入日志信息表            
            strSql += " INSERT INTO Sys_OperateOrderLog ";
            strSql += " (OrderId,TaskId,OperateType,OperateName,OperUrl,ParamValue,BeforeContent,AfterContent,OperateDescribe,OperateUserId,OperateUserName,OperateTime) ";
            strSql += " values('" + OrderId + "'";
            strSql += ",'" + TaskId + "'";
            strSql += ",'4'";
            strSql += ",'订单拆户'";
            strSql += ",'/api/FormEngine/SaveFormData'";
            strSql += ",'-Form201810121713050001'";    //修改
            strSql += ",''";
            strSql += ",''";
            strSql += ",'" + OperateDescribe + "'";
            strSql += ",'" + UserId + "'";
            strSql += ",'" + UserName + "'";
            strSql += ",'" + timenow + "'";
            strSql += ");";
            
            StringBuilder sb = new StringBuilder();
            sb.Append(strSql);
            //DbHelper dbHelper = new DbHelper(e.Form.DbIns, CPAppContext.CurDbType());
            if (sb.Length > 0)
            {
                dbHelper.ExecuteNonQuery(sb.ToString());
            }
        }
    }


    /// <summary>
    /// 订单换户
    /// 1、插入日志，记录拆户操作
    /// 2、更新任务与车辆关系表 车辆运输状态 
    /// </summary>
    public class OrderChangeLog : CPFrameWork.UIInterface.Form.ICPFormAfterSave
    {
        public void AfterSave(ICPFormAfterSaveEventArgs e)
        {
            string TaskId = e.GetFieldValue(e.Form.MainTableName, "TaskId", 0);
            string OrderId = e.GetFieldValue(e.Form.MainTableName, "OrderId", 0);
            string UserId = e.GetFieldValue(e.Form.MainTableName, "CreateUserId", 0);
            string UserName = e.GetFieldValue(e.Form.MainTableName, "CreateUserName", 0);
            string CustomerName = e.GetFieldValue(e.Form.MainTableName, "CustomerName", 0);
            string timenow = DateTime.Now.ToString();

            string OperateDescribe = UserName + "在" + timenow + "对任务" + TaskId + "、订单" + OrderId + "进行了换户操作，换给了" + CustomerName;
            //插入日志信息表            
            string strSql = "INSERT INTO Sys_OperateOrderLog ";
            strSql += " (OrderId,TaskId,OperateType,OperateName,OperUrl,ParamValue,BeforeContent,AfterContent,OperateDescribe,OperateUserId,OperateUserName,OperateTime) ";
            strSql += " values('" + OrderId + "'";
            strSql += ",'" + TaskId + "'";
            strSql += ",'5'";
            strSql += ",'订单换户'";
            strSql += ",'/api/FormEngine/SaveFormData'";
            strSql += ",'-Form201810121646210001'";    //修改
            strSql += ",''";
            strSql += ",''";
            strSql += ",'" + OperateDescribe + "'";
            strSql += ",'" + UserId + "'";
            strSql += ",'" + UserName + "'";
            strSql += ",'" + timenow + "'";
            strSql += ");";
            //更新任务与车辆关系表 车辆运输状态为“已换户” 
            strSql += " Update YW_TaskCarRelation ";
            strSql += " set CarDeliveryStatus = '5' ";
            strSql += " where TaskId  = '" + TaskId + "' and OrderId  = '" + OrderId + "' and (MainDriverId= '" + UserId + "' or AssistantDriverId= '" + UserId + "');";
            StringBuilder sb = new StringBuilder();
            sb.Append(strSql);
            DbHelper dbHelper = new DbHelper(e.Form.DbIns, CPAppContext.CurDbType());
            if (sb.Length > 0)
            {
                dbHelper.ExecuteNonQuery(sb.ToString());
            }

        }
    }

    /// <summary>
    /// 报废填报（部分报废，全部报废）  填写完成后，直接签收
    /// 1、部分报废签收的话在签字信息表插入一条记录。
    /// 2、更新任务与车辆关系表，车辆运输状态为“已完成”，完成类型为“部分报废签收/全部报废”。
    /// 3、插入日志，记录报废操作。
    /// </summary>
    public class OrderBaoFeiLog : CPFrameWork.UIInterface.Form.ICPFormAfterSave
    {
        public void AfterSave(ICPFormAfterSaveEventArgs e)
        {
            StringBuilder stringb_order = new StringBuilder();
            DbHelper dbHelper = new DbHelper(e.Form.DbIns, CPAppContext.CurDbType());
            string TaskId = e.GetFieldValue(e.Form.MainTableName, "TaskId", 0);
            string OrderId = e.GetFieldValue(e.Form.MainTableName, "OrderId", 0);
            string Type = e.GetFieldValue(e.Form.MainTableName, "Type", 0);//报废类型 1部分报废 2全部报废 
            string UserId = e.GetFieldValue(e.Form.MainTableName, "CreateUserId", 0);
            string UserName = e.GetFieldValue(e.Form.MainTableName, "CreateUserName", 0);
            string SignCode = e.GetFieldValue(e.Form.MainTableName, "SignCode", 0);
            string timenow = DateTime.Now.ToString();
            string strSql = "";
            string strlogname = "";
            string finishType = "";
            string CustomerName ="";
            string CustomerState = "";
            string CustomerCity = "";
            string CustomerDistrict = "";
            string CustomerAddress = "";
            string CustomerZip = "";
            string CustomerMobile = "";
            string CustomerPhone = "";
            string user_id = "";//买家id
            string shop_id = "";//买家id
            string currentTime = DateTime.Now.ToString();
            //获取订单中的客户信息
            string strSql_order = "SELECT distinct CustomerName,CustomerState,CustomerCity,CustomerDistrict,CustomerAddress,CustomerZip,CustomerMobile,CustomerPhone,t.user_id,t.shop_id from YW_OrderInfo as o left join O_systrade_trade as t on o.OrderCode = t.tid ";
            strSql_order += " where OrderCode = '" + OrderId + "';";
            stringb_order.Append(strSql_order);
            DataTable dtOrderInfo = dbHelper.ExecuteDataSet(stringb_order.ToString()).Tables[0];
            if (dtOrderInfo.Rows.Count > 0) {
                CustomerName = dtOrderInfo.Rows[0][0].ToString();
                CustomerState = dtOrderInfo.Rows[0][1].ToString();
                CustomerCity = dtOrderInfo.Rows[0][2].ToString();
                CustomerDistrict = dtOrderInfo.Rows[0][3].ToString();
                CustomerAddress = dtOrderInfo.Rows[0][4].ToString();
                CustomerZip = dtOrderInfo.Rows[0][5].ToString();
                CustomerMobile = dtOrderInfo.Rows[0][6].ToString();
                CustomerPhone = dtOrderInfo.Rows[0][7].ToString();
                user_id = dtOrderInfo.Rows[0][8].ToString();
                shop_id = dtOrderInfo.Rows[0][9].ToString();
            }                
             
            //部分报废：完成类型为“部分报废签收”，需要新增签收信息
            if (Type == "1") {
                strlogname = "部分报废";
                finishType = "5";
                //保存签字图片  
                string signFilePath = "SignImages";
                string FilePath = CPAppContext.HostingEnvironment.ContentRootPath + "\\wwwroot\\Style\\" + signFilePath + "\\";
                if (System.IO.Directory.Exists(FilePath) == false)
                    System.IO.Directory.CreateDirectory(FilePath);
                string SignPath = "/Style/" + signFilePath + "/" + Base64Code.SaveFile(SignCode, FilePath, ".png");
                
               
                //新增签收信息
                string SignType = "5";
                strSql += "INSERT INTO YW_CustomerSign ";
                strSql += "(TaskId,OrderId,SignPath,CustomerName,CustomerState,CustomerCity,CustomerDistrict,CustomerAddress,CustomerZip,CustomerMobile,CustomerPhone,SignType,IsSign,CreateUserId,SignTime) ";
                strSql += "values('" + TaskId + "'";
                strSql += ",'" + OrderId + "'";
                strSql += ",'" + SignPath + "'";                
                strSql += ",'" + CustomerName + "'";
                strSql += ",'" + CustomerState + "'";
                strSql += ",'" + CustomerCity + "'";
                strSql += ",'" + CustomerDistrict + "'";
                strSql += ",'" + CustomerAddress + "'";
                strSql += ",'" + CustomerZip + "'";
                strSql += ",'" + CustomerMobile + "'";
                strSql += ",'" + CustomerPhone + "'";
                strSql += ",'" + SignType + "'";
                strSql += ",'1'";
                strSql += ",'" + UserId + "'";
                strSql += ",'" + currentTime + "'";
                strSql += ");";
            }
            //全部报废：完成类型为“全部报废”，
            else if (Type == "2")
            {
                strlogname = "全部报废";
                finishType = "7";
            }

            //更新任务与车辆关系表 车辆运输状态为“已完成”，完成类型为“部分报废签收(5)/全部报废(7)” 
            strSql += " Update YW_TaskCarRelation ";
            strSql += " set CarDeliveryStatus = '2' ";
            strSql += ",FinishType = '" + finishType + "' ";
            strSql += " where TaskId  = '" + TaskId + "' and OrderId  = '" + OrderId + "' and (MainDriverId= '" + UserId + "' or AssistantDriverId= '" + UserId + "');";
            //插入日志信息表     
            string OperateDescribe = UserName + "在" + timenow + "对任务" + TaskId + "、订单" + OrderId + "进行了"+ strlogname + "操作" ;                  
            strSql += "INSERT INTO Sys_OperateOrderLog ";
            strSql += " (OrderId,TaskId,OperateType,OperateName,OperUrl,ParamValue,BeforeContent,AfterContent,OperateDescribe,OperateUserId,OperateUserName,OperateTime) ";
            strSql += " values('" + OrderId + "'";
            strSql += ",'" + TaskId + "'";
            strSql += ",'5'";
            strSql += ",'"+ strlogname + "'";
            strSql += ",'/api/FormEngine/SaveFormData'";
            strSql += ",'-Form201810291104500001'";    //修改
            strSql += ",''";
            strSql += ",''";
            strSql += ",'" + OperateDescribe + "'";
            strSql += ",'" + UserId + "'";
            strSql += ",'" + UserName + "'";
            strSql += ",'" + timenow + "'";
            strSql += ");";
           
            StringBuilder sb = new StringBuilder();
            sb.Append(strSql);
            if (sb.Length > 0)
            {
                dbHelper.ExecuteNonQuery(sb.ToString());
            }
            //调取确认收货接口
            ConfirmRecieve confirmRecieve = new ConfirmRecieve();
            confirmRecieve.SynRecieve(TaskId, OrderId, shop_id, user_id, UserId, UserName);
        }
    }
}
